package com.zenob.secalendar.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.zenob.common.log.Log;

public class HttpEngine {

	private final static String TAG = "HttpEngine";
	
	 private HttpConnection	 mConnection = null;
	 private OutputStream	 mRequestStream = null;
	 
	 
	 private InputStream 	 mResponseStream = null;
	 private byte[]			 mResponseData = null;
	 
	 private int 			mResponseCode;
	 
	 public HttpEngine() {
		 
	 }
	 
	 public void sendPost(String url, InputStream postData, String contentType) throws IOException {
		
		 Log.d(TAG, "sendPost "+url);
		 
		mConnection = null;
		mRequestStream = null;
		mResponseStream = null;
		mResponseData = null;
		 
		 mConnection = (HttpConnection) Connector.open(url);
		 
		 mConnection.setRequestMethod(HttpConnection.POST);
		 mConnection.setRequestProperty("Content-Type", contentType);
		 
		 byte[] buffer = new byte[1024];
		 
		 mRequestStream = mConnection.openOutputStream();
		 
		 int recv = -1;
		 
		 while( (recv = postData.read(buffer) ) != -1 ) {
			 mRequestStream.write(buffer, 0, recv);
		 }
		 
		 mResponseCode = mConnection.getResponseCode();
		 
         if (mResponseCode == HttpConnection.HTTP_TEMP_REDIRECT ||
        	 mResponseCode == HttpConnection.HTTP_MOVED_TEMP ||
             mResponseCode == HttpConnection.HTTP_MOVED_PERM) {
             // Get the new location and close the connection
             url = mConnection.getHeaderField("location");
             mConnection.close();
             Log.i(TAG, "Redirecting to " + url);
         } 

	 }
}
